/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.eplatform.modules.sys.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.eplatform.common.config.Global;
import com.eplatform.common.utils.ExtData;
import com.eplatform.common.utils.FileUtils;
import com.eplatform.common.web.BaseController;
import com.eplatform.modules.sys.utils.UserUtils;

/**
 * 文件上传Controller
 * @author ThinkGem
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/fileinput")
public class FileinputController extends BaseController {
	
	/**
	 * 文件上传
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = {"","index"})
	@ResponseBody()
	public Map treeselect(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 String userId=UserUtils.getUser().getId();
		 String year=String.valueOf(new Date().getYear());
		 String month=String.valueOf(new Date().getMonth());
		 String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL
					+ userId + "/" + year +"/"+ month;
		 if(!FileUtils.existDirectory(FileUtils.path(realPath))){
			 FileUtils.createDirectory(FileUtils.path(realPath));
		 }
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 Iterator<String> fileIterator = multipartRequest.getFileNames();
		 String path="";
		 while (fileIterator.hasNext()) {
	            String fileKey = fileIterator.next();
	            logger.debug("文件名为：" + fileKey);

	            // 获取对应文件
	            MultipartFile multipartFile = fileMap.get(fileKey);
	            
	            if (multipartFile.getSize() != 0L) {
	            	File file=new File(FileUtils.path(realPath+"/"+multipartFile.getOriginalFilename()));
	            	multipartFile.transferTo(file);    
	            	path=file.getName();
	            }
		 }
		 if(StringUtils.isNotBlank(path))
		 return ExtData.Result.SuccessData(request.getContextPath()+"/"+ Global.USERFILES_BASE_URL
					+ userId + "/" + year +"/"+ month+"/"+path); 
		 else
			 return ExtData.Result.Error("上传失败！");
	}
	
	
}
